package com.cupk.services;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cupk.dtos.ChangePasswordRequest;
import com.cupk.dtos.UpdateUserRequest;
import com.cupk.dtos.UserDto;
import com.cupk.entities.User;
import com.cupk.exceptions.ResourceNotFoundException;
import com.cupk.mapper.UserMapper; // 1. 【修改】: 导入 UserMapper
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class UserService {

    private final UserMapper userMapper; // 2. 【修改】: 注入 UserMapper
    private final PasswordEncoder passwordEncoder; // 注入密码编码器
    private final FileService fileService;

    @Transactional(readOnly = true)
    public List<UserDto> getAllUsersForSelection() {
        // 3. 【修改】: 使用 userMapper.selectList(null) 来查询所有用户
        // null 表示没有查询条件
        List<User> users = userMapper.selectList(null);

        return users.stream()
                .map(this::convertToDto)
                .collect(Collectors.toList());
    }
    @Transactional
    public String updateUserAvatar(String username, MultipartFile file) {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        if (user == null) {
            throw new ResourceNotFoundException("用户未找到: " + username);
        }

        // 调用通用文件服务上传文件，指定分类为 'avatars'
        String avatarUrl = fileService.uploadFile(file, "avatars", username);

        // 将返回的文件访问 URL 保存到用户实体
        user.setAvatarUrl(avatarUrl);
        userMapper.updateById(user);

        log.info("用户 {} 的头像已更新，新 URL: {}", username, avatarUrl);

        return avatarUrl;
    }
    private UserDto convertToDto(User user) {
        UserDto dto = new UserDto();
        dto.setId(user.getId());
        dto.setUsername(user.getUsername());
        dto.setFullName(user.getFullName());
        dto.setEmail(user.getEmail());
        dto.setPhoneNumber(user.getPhoneNumber());
        dto.setDepartment(user.getDepartment());
        dto.setRole(user.getRole());
        dto.setStatus(user.getStatus()); // 现在都是String类型
        return dto;
    }

    /**
     * 根据用户名获取用户个人资料
     */
    @Transactional(readOnly = true)
    public UserDto getUserProfile(String username) {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        if (user == null) {
            throw new ResourceNotFoundException("未找到用户：" + username);
        }
        return convertToDto(user);
    }

    /**
     * 更新用户个人资料
     */
    @Transactional
    public UserDto updateUserProfile(String username, UpdateUserRequest request) {
        log.info("开始更新用户资料，用户名: {}", username);
        log.info("请求数据: {}", request);

        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        if (user == null) {
            throw new ResourceNotFoundException("未找到用户：" + username);
        }

        log.info("更新前用户数据: id={}, phoneNumber={}", user.getId(), user.getPhoneNumber());

        // 更新用户信息
        if (request.getFullName() != null && !request.getFullName().trim().isEmpty()) {
            user.setFullName(request.getFullName().trim());
        }

        if (request.getDepartment() != null) {
            if (request.getDepartment().trim().isEmpty()) {
                user.setDepartment(null); // 允许清空部门
            } else {
                user.setDepartment(request.getDepartment().trim());
            }
        }

        if (request.getEmail() != null && !request.getEmail().trim().isEmpty()) {
            // 检查邮箱是否被其他用户使用
            User existingUser = userMapper.selectOne(new QueryWrapper<User>()
                    .eq("email", request.getEmail())
                    .ne("id", user.getId()));
            if (existingUser != null) {
                throw new IllegalArgumentException("该邮箱已被其他用户使用");
            }
            user.setEmail(request.getEmail().trim());
        }

        if (request.getPhoneNumber() != null) {
            log.info("处理手机号更新，原始值: '{}', 长度: {}", request.getPhoneNumber(), request.getPhoneNumber().length());
            if (request.getPhoneNumber().trim().isEmpty()) {
                log.info("手机号为空，设置为null");
                user.setPhoneNumber(null); // 允许清空手机号
            } else {
                String trimmedPhone = request.getPhoneNumber().trim();
                log.info("手机号不为空，处理后的值: '{}'", trimmedPhone);
                // 检查手机号是否被其他用户使用（只有当手机号不为空时才检查）
                User existingUser = userMapper.selectOne(new QueryWrapper<User>()
                        .eq("phone_number", trimmedPhone)
                        .ne("id", user.getId()));
                if (existingUser != null) {
                    log.warn("手机号已被其他用户使用: {}", trimmedPhone);
                    throw new IllegalArgumentException("该手机号已被其他用户使用");
                }
                log.info("设置新手机号: {}", trimmedPhone);
                user.setPhoneNumber(trimmedPhone);
            }
        } else {
            log.info("请求中没有手机号字段");
        }

        if (request.getStatus() != null && !request.getStatus().trim().isEmpty()) {
            user.setStatus(request.getStatus().trim());
        }

        // 保存更新 - 使用UpdateWrapper确保所有字段都被更新
        log.info("更新后用户数据: id={}, phoneNumber={}", user.getId(), user.getPhoneNumber());

        // 使用UpdateWrapper来明确更新字段，包括null值
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", user.getId());

        // 明确设置要更新的字段
        if (request.getFullName() != null) {
            updateWrapper.set("full_name", user.getFullName());
        }
        if (request.getDepartment() != null) {
            updateWrapper.set("department", user.getDepartment());
        }
        if (request.getEmail() != null) {
            updateWrapper.set("email", user.getEmail());
        }
        if (request.getPhoneNumber() != null) {
            updateWrapper.set("phone_number", user.getPhoneNumber());
            log.info("明确设置phone_number字段为: {}", user.getPhoneNumber());
        }
        if (request.getStatus() != null) {
            updateWrapper.set("status", user.getStatus());
        }

        int updateResult = userMapper.update(null, updateWrapper);
        log.info("数据库更新结果: {}", updateResult);

        // 重新查询验证更新结果
        User updatedUser = userMapper.selectById(user.getId());
        log.info("重新查询后的用户数据: id={}, phoneNumber={}", updatedUser.getId(), updatedUser.getPhoneNumber());

        return convertToDto(updatedUser);
    }

    /**
     * 修改用户密码
     */
    @Transactional
    public void changePassword(String username, ChangePasswordRequest request) {
        // 验证新密码和确认密码是否一致
        if (!request.getNewPassword().equals(request.getConfirmPassword())) {
            throw new IllegalArgumentException("新密码和确认密码不一致");
        }

        // 查找用户
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        if (user == null) {
            throw new ResourceNotFoundException("未找到用户：" + username);
        }

        // 验证当前密码是否正确
        if (!passwordEncoder.matches(request.getCurrentPassword(), user.getPassword())) {
            throw new IllegalArgumentException("当前密码不正确");
        }

        // 检查新密码是否与当前密码相同
        if (passwordEncoder.matches(request.getNewPassword(), user.getPassword())) {
            throw new IllegalArgumentException("新密码不能与当前密码相同");
        }

        // 更新密码
        user.setPassword(passwordEncoder.encode(request.getNewPassword()));
        userMapper.updateById(user);
    }
}